import { fail } from "assert";

var Net = require("Net")
var Global = require("Global")
cc.Class({
    extends: cc.Component,

    properties: {
        lblName: cc.Label,
        // lblMoney: cc.Label,
        lblGems: cc.Label,
        lblID: cc.Label,
        lblNotice: cc.Label,
        joinGameWin: cc.Node,
        createRoomWin: cc.Node,
        resultsWin: cc.Node,
        ruleWin: cc.Node,
        shareWin: cc.Node,
        dealingsWin: cc.Node,
        invitecodeWin: cc.Node,
        gemsWin: cc.Node,
        btnJoinGame: cc.Node,
        sprHeadImg: cc.Sprite,
        // extension: cc.Node,
        _tradelist: null,
        _viewitemTemp: null,
        _viewlist: null,
        _num: 0
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    initNetHandlers: function () {
        var self = this;
    },

    onShare: function () {
        cc.vv.anysdkMgr.share("小五牌坊", "小五牌坊，包含了乐平本地麻将、牛牛、九点半多个玩法。");
    },
    onShareLine: function () {
        cc.vv.anysdkMgr.shareline("小五牌坊", "小五牌坊，包含了乐平本地麻将、牛牛、九点半多个玩法。");
    },
    onShopping: function () {
        console.log('这里是购买的地方')
        // cc.vv.anysdkMgr.shopping("小五牌坊", "小五牌坊，包含了乐平本地麻将、牛牛、九点半多个玩法。");
    },
    // use this for initialization
    onLoad: function () {
        if (!cc.sys.isNative && cc.sys.isMobile) {
            var cvs = this.node.getComponent(cc.Canvas);
            cvs.fitHeight = true;
            cvs.fitWidth = true;
        }
        if (!cc.vv) {
            cc.director.loadScene("loading");
            return;
        }
        this.initLabels();
        var roomId = cc.vv.userMgr.oldRoomId;
        if (roomId != null) {
            cc.vv.userMgr.oldRoomId = null;
            cc.vv.userMgr.enterRoom(roomId);
        }

        var imgLoader = this.sprHeadImg.node.getComponent("ImageLoader");
        imgLoader.setUserID(cc.vv.userMgr.userId);
        cc.vv.utils.addClickEvent(this.sprHeadImg.node, this.node, "Hall", "onBtnClicked");
        this._tradelist = cc.find("Canvas/tradelist");
        this._tradelist = this.node.getChildByName("tradelist");

        this._viewlist = this._tradelist.getChildByName("viewlist");
        this._tradelist = cc.find("view/content", this._viewlist);

        this._viewitemTemp = this._tradelist.children[0];
        this._tradelist.removeChild(this._viewitemTemp);

        this.addComponent("UserInfoShow");
        // this.initButtonHandler("Canvas/top_right/btn_dealings");
        // this.initButtonHandler("Canvas/top_right/btn_rule");
        // this.initButtonHandler("Canvas/top_right/btn_results");
        this.dealingsWin.addComponent("OnBack");
        this.ruleWin.addComponent("OnBack");
        this.shareWin.addComponent("OnBack");
        this.resultsWin.addComponent("OnBack");
        this.invitecodeWin.addComponent("OnBack");
        this.gemsWin.addComponent("OnBack");
        // this.joinGameWin.addComponent("OnBack");
        // this.createRoomWin.addComponent("OnBack");

        if (!cc.vv.userMgr.notice) {
            cc.vv.userMgr.notice = {
                version: null,
                msg: "数据请求中...",
            }
        }

        if (!cc.vv.userMgr.gemstip) {
            cc.vv.userMgr.gemstip = {
                version: null,
                msg: "数据请求中...",
            }
        }

        this.lblNotice.string = cc.vv.userMgr.notice.msg;

        this.refreshInfo();
        this.refreshNotice();
        this.refreshGemsTip();

        cc.vv.audioMgr.playBGM("bgMain.mp3");
        this.invitecodeWin.active = !cc.vv.userMgr.invitestate //== 0 ? true : false;
        console.log(cc.vv.userMgr.invitestate + '-----cc.vv.userMgr.invitestate')
        // setTimeout(function () {
        //     cc.vv.alert.show("absgjd");
        // }, 3000)
        // if (this._num == 0) {
        cc.vv.gameNetMgr.connectHallServer(cc.vv.userMgr.hallsocket, 'hallInfo', 'hall');
        // }

    },

    initEventHandlers: function () {
        cc.vv.gameNetMgr.dataEventHandler = this.node;
        var self = this;
        this.node.on('hall_message', function (data) {
            console.log("hall_message");
            console.log(data.detail)
            // self.lblName.string = data.gems
        });
    },
    refreshInfo: function () {
        var self = this;
        var onGet = function (ret) {
            if (ret.errcode !== 0) {
                console.log(ret.errmsg);
            }
            else {
                if (ret.gems != null) {
                    this.lblGems.string = ret.gems;
                }
            }
        };

        var data = {
            account: cc.vv.userMgr.account,
            sign: cc.vv.userMgr.sign,
        };
        cc.vv.http.sendRequest("/get_user_status", data, onGet.bind(this));
    },

    refreshGemsTip: function () {
        var self = this;
        var onGet = function (ret) {
            if (ret.errcode !== 0) {
                console.log(ret.errmsg);
            }
            else {
                cc.vv.userMgr.gemstip.version = ret.version;
                cc.vv.userMgr.gemstip.msg = ret.msg.replace("<newline>", "\n");
            }
        };

        var data = {
            account: cc.vv.userMgr.account,
            sign: cc.vv.userMgr.sign,
            type: "fkgm",
            version: cc.vv.userMgr.gemstip.version
        };
        cc.vv.http.sendRequest("/get_message", data, onGet.bind(this));
    },

    refreshNotice: function () {
        var self = this;
        var onGet = function (ret) {
            if (ret.errcode !== 0) {
                console.log(ret.errmsg);
            }
            else {
                console.log(ret.msg + '----')
                cc.vv.userMgr.notice.version = ret.version;
                cc.vv.userMgr.notice.msg = ret.msg;
                this.lblNotice.string = ret.msg;
            }
        };

        var data = {
            account: cc.vv.userMgr.account,
            sign: cc.vv.userMgr.sign,
            type: "notice",
            version: cc.vv.userMgr.notice.version
        };
        cc.vv.http.sendRequest("/get_message", data, onGet.bind(this));
    },

    initButtonHandler: function (btnPath) {
        var btn = cc.find(btnPath);
        cc.vv.utils.addClickEvent(btn, this.node, "Hall", "onBtnClicked");
    },

    initLabels: function () {
        let invitenum = cc.find('Canvas/share/sharenum').getComponent(cc.Label);
        this.lblName.string = cc.vv.userMgr.userName;
        if (cc.vv.userMgr.invitenum > 0) {
            invitenum.string = '您的邀请码是【' + cc.vv.userMgr.invitecode + '】\n成功邀请' + cc.vv.userMgr.invitenum + '个好\n已获得' + cc.vv.userMgr.invitenum + '个房豆，继续加油哦^_^';
        } else {
            invitenum.string = '您的邀请码是【' + cc.vv.userMgr.invitecode + '】\n赶紧邀请好友获得房豆吧！^_^';
        }
        this.lblGems.string = cc.vv.userMgr.gems;
        this.lblID.string = "ID: " + cc.vv.userMgr.userId;
    },

    onBtnClicked: function (event) {
        if (event.target.name == "btn_rule") {
            this.ruleWin.active = true;
        }
        // else if (event.target.name == "btn_give") {
        //     this.gemsWin.active = true;
        // }
        else if (event.target.name == "btn_share") {
            this.shareWin.active = true;
        }
        else if (event.target.name == "btn_results") {
            this.resultsWin.active = true;
        }
    },
    // onBtndealingsClicked: function () {
    //     this.dealingsWin.active = true;
    // },

    onTest: function () {
        cc.vv.anysdkMgr.shareResult();
    },
    onInvitation: function () {
        var invitecode = cc.find("Canvas/invitationin/input").getComponent(cc.EditBox);
        if (invitecode.string == '') {
            cc.vv.alert.show("邀请码不能为空");
            return;
        }
        var fn = function (ret) {
            console.log(ret)
            if (ret.errcode === 0) {
            }
            else {
            }
        }
        var data = {
            userid: parseInt(cc.vv.userMgr.userId),
            account: cc.vv.userMgr.account,
            sign: cc.vv.userMgr.sign,
            code: invitecode.string
        };
        cc.vv.http.sendRequest("/get_invitation_gems", data, fn);
    },
    onInvitationNo: function () {
        this.invitecodeWin.active = false;
        cc.vv.alert.show("确定无好友邀请，今后不在弹窗提示！", function () {
            var fn = function (ret) {
                console.log(ret)
                if (ret.errcode === 1) {
                    cc.vv.userMgr.invitestate = 1;
                }
                else {
                }
            }
            var data = {
                userid: parseInt(cc.vv.userMgr.userId),
                account: cc.vv.userMgr.account,
                sign: cc.vv.userMgr.sign
            };
            cc.vv.http.sendRequest("/get_invitation_gems_no", data, fn);
        }, true);
    },
    onDealingsGems: function (e) {
        var otheruserid = this.dealingsWin.getChildByName('userID').getChildByName('inputID').getComponent(cc.EditBox);
        var gemsnum = this.dealingsWin.getChildByName('gemsNum').getChildByName('inoutNUM').getComponent(cc.EditBox);
        var usergems = cc.find("Canvas/top_left/headinfo/lblGems/label").getComponent(cc.Label);
        var _this = this;
        if (parseInt(gemsnum.string) > parseInt(usergems.string) || otheruserid.string == '' || gemsnum.string == '') {
            cc.vv.alert.show("请输入正确的赠送信息");
        } else {
            if (otheruserid != '' && gemsnum != '') {
                var fn = function (ret) {
                    console.log(ret)
                    if (ret.errcode === 0) {
                        cc.vv.alert.show("房豆不足，赠送失败");
                    }
                    else {
                        //这里提示用户赠送成功，并且修改自身的赠送数量
                        if (ret.gems) {
                            cc.vv.alert.show("赠送成功");
                            usergems.string = ret.gems;
                            _this.dealingsWin.active = false;
                            var result = {
                                userid: parseInt(otheruserid.string),
                                otheruserid: parseInt(cc.vv.userMgr.userId),
                                gems: parseInt(gemsnum.string),
                                msg: 'asdjkhsd'
                            }
                            cc.vv.gameNetMgr.sendmsg(result);
                        }
                    }
                }
                var data = {
                    account: cc.vv.userMgr.account,
                    gemsnum: parseInt(gemsnum.string),
                    otheruserid: parseInt(otheruserid.string),
                    sign: cc.vv.userMgr.sign,
                    userid: parseInt(cc.vv.userMgr.userId),
                };
                cc.vv.http.sendRequest("/dealings_gems", data, fn);
            } else {
                cc.vv.alert.show("请填写正确的信息");
                return;
            }
        }
    },
    onGemsHistory: function () {
        this.gemsWin.active = true;
        var _this = this;
        var onGet = function (ret) {
            if (ret.errcode === 0) {
                cc.vv.alert.show("耐心等待消息列表");
            }
            else {
                var usergems = cc.find("Canvas/top_left/headinfo/lblGems/label").getComponent(cc.Label);
                var tishi = cc.find("Canvas/tradelist/label");
                usergems.string = ret.gems;
                if (ret.tradelist == '' || ret.tradelist == null) {
                    tishi.active = true;
                } else {
                    var datalist = JSON.parse(ret.tradelist);
                    tishi.active = false;
                    for (var i = 0; i < datalist.length; ++i) {
                        var node = _this.getViewItem(i);
                        var str = node.getChildByName("textlist").getComponent(cc.Label);
                        if (datalist[i].type == 1) {
                            //2016-09-03 17:07:19 赠送ID为123456的10000张房豆已收到。
                            str.string = (i + 1) + '. ' + _this.dateFormat(datalist[i].time * 1000) + ' 赠送ID【' + datalist[i].plusid + '】好友' + datalist[i].gemsnum + '个房豆。';
                        } else if (datalist[i].type == 2) {
                            //2016-09-03 17:07:19 已收到ID为123456赠送的10000张房豆。
                            str.string = (i + 1) + '. ' + _this.dateFormat(datalist[i].time * 1000) + ' 收到ID【' + datalist[i].plusid + '】好友赠送的' + datalist[i].gemsnum + '个房豆。';
                        }

                    }
                    _this.shrinkContent(datalist.length);
                }
            }
        };
        var data = {
            account: cc.vv.userMgr.account,
            sign: cc.vv.userMgr.sign,
        };
        cc.vv.http.sendRequest("/get_history_gems", data, onGet);
    },
    dateFormat: function (time) {
        var date = new Date(time);
        var datetime = "{0}-{1}-{2} {3}:{4}:{5}";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        month = month >= 10 ? month : ("0" + month);
        var day = date.getDate();
        day = day >= 10 ? day : ("0" + day);
        var h = date.getHours();
        h = h >= 10 ? h : ("0" + h);
        var m = date.getMinutes();
        m = m >= 10 ? m : ("0" + m);
        var s = date.getSeconds();
        s = s >= 10 ? s : ("0" + s);
        datetime = datetime.format(year, month, day, h, m, s);
        return datetime;
    },
    getViewItem: function (index) {
        var content = this._tradelist;
        if (content.childrenCount > index) {
            return content.children[index];
        }
        var node = cc.instantiate(this._viewitemTemp);
        content.addChild(node);
        return node;
    },
    shrinkContent: function (num) {
        while (this._tradelist.childrenCount > num) {
            var lastOne = this._tradelist.children[this._content.childrenCount - 1];
            this._tradelist.removeChild(lastOne, true);
        }
    },
    onJoinGameClicked: function () {
        this.joinGameWin.active = true;
    },
    onInfoHead: function () {
        cc.vv.userinfoShow.show(cc.vv.userMgr.userName, cc.vv.userMgr.userId, this.sprHeadImg, cc.vv.userMgr.sex, cc.vv.userMgr.ip);
    },
    onRoomCard: function () {
        var daili = this.dealingsWin.getChildByName('daili').getComponent(cc.Label)
        var dailiarr = cc.vv.userMgr.notice.msg.split('：')
        daili.string = '代理咨询【微信号】' + dailiarr[1]
        this.dealingsWin.active = true;
    },
    onReturnGameClicked: function () {
        console.log(cc.vv.gameNetMgr.conf.type)
        if (cc.vv.gameNetMgr.conf.type == "mj") {
            cc.director.loadScene("mjgame");
        } else if (cc.vv.gameNetMgr.conf.type == "nn") {
            cc.director.loadScene("nngame");
        } else if (cc.vv.gameNetMgr.conf.type == "jdb") {
            cc.director.loadScene("jdbgame");
        }
    },

    onBtnAddGemsClicked: function () {
        cc.vv.alert.show(cc.vv.userMgr.gemstip.msg);
        this.refreshInfo();
    },

    onCreateRoomClicked: function () {
        if (cc.vv.gameNetMgr.roomId != null) {
            cc.vv.alert.show("房间已经创建!\n必须解散当前房间才能创建新的房间");
            return;
        }
        console.log("onCreateRoomClicked");
        this.createRoomWin.active = true;
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        var x = this.lblNotice.node.x;
        x -= dt * 100;
        if (x + this.lblNotice.node.width < -1000) {
            x = 500;
        }
        this.lblNotice.node.x = x;

        if (cc.vv && cc.vv.userMgr.roomData != null) {
            cc.vv.userMgr.enterRoom(cc.vv.userMgr.roomData);
            cc.vv.userMgr.roomData = null;
        }
    },
});
